package com.example.myapplicationfinalwork.ui.history;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.myapplicationfinalwork.MainActivity;
import com.example.myapplicationfinalwork.R;
import com.example.myapplicationfinalwork.common.Analysis;
import com.example.myapplicationfinalwork.common.HistoryWeather;
import com.example.myapplicationfinalwork.common.Weather;
import com.example.myapplicationfinalwork.common.WeatherDesc;
import com.example.myapplicationfinalwork.common.db.dao.CityDao;
import com.example.myapplicationfinalwork.common.db.database.CityDatabase;
import com.example.myapplicationfinalwork.common.db.table.InterestedCity;
import com.example.myapplicationfinalwork.controller.OkHttpController;
import com.example.myapplicationfinalwork.databinding.FragmentHistoryBinding;
import com.example.myapplicationfinalwork.model.HistoryViewModel;
import com.example.myapplicationfinalwork.ui.weather.WeatherTodayFragment;
import com.example.myapplicationfinalwork.util.WeatherChartView;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class HistoryFragment extends Fragment {
    private static final String TAG="historyFragment";
    private HistoryViewModel historyViewModel;
    private FragmentHistoryBinding binding;
    private List<HistoryWeather> listData=new ArrayList<>();
    private List<String> listCity=new ArrayList<>();
    private Gson gson=new Gson();
    private Handler handler=new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if(msg.what==1){
                Log.i(TAG, "handleMessage: "+msg.obj.toString());
                Bundle bundle=msg.getData();
                HistoryWeather historyTmp=new HistoryWeather();
                historyTmp.setNowTem(bundle.getString("nowTem")+"℃");
                historyTmp.setDate(bundle.getString("date"));

                JSONObject data=(JSONObject) msg.obj;
                try {
                    historyTmp.setCity(data.getString("city"));
                    int[] high=new int[6];
                    int[] low=new int[6];
                    JSONObject yesterday=data.getJSONObject("yesterday");
                    high[0]=Analysis.getNumOfTemperature(yesterday.getString("high"));
                    low[0]=Analysis.getNumOfTemperature(yesterday.getString("low"));

                    JSONArray forecast=data.getJSONArray("forecast");
                    for(int i=0;i<forecast.length();++i){
                        Weather tmp=gson.fromJson(forecast.getJSONObject(i).toString(),Weather.class);
                        high[i+1]=Analysis.getNumOfTemperature(tmp.getHigh());
                        low[i+1]=Analysis.getNumOfTemperature(tmp.getLow());
                    }
                    historyTmp.setHigh(high);
                    historyTmp.setLow(low);
                    listData.add(historyTmp);
                    historyViewModel.setListData(listData);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    };
    private OkHttpController okHttpController=new OkHttpController(handler);

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        historyViewModel =
                new ViewModelProvider(this).get(HistoryViewModel.class);

        binding = FragmentHistoryBinding.inflate(inflater, container, false);
        listData.clear();


        historyViewModel.getListCity(((MainActivity)getActivity()).username).observe(getViewLifecycleOwner(), new Observer<List<InterestedCity>>() {
            @Override
            public void onChanged(List<InterestedCity> cities) {
                for(InterestedCity v:cities){
                    okHttpController.getWeather(v.getCityName(),v.getTime());
                }
            }
        });

        historyViewModel.getListData().observe(getViewLifecycleOwner(), new Observer<List<HistoryWeather>>() {
            @Override
            public void onChanged(List<HistoryWeather> historyWeathers) {
                Log.i(TAG, "更新recycleView ");
                RecyclerView rv=binding.rvHistoryList;
                LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
                rv.setLayoutManager(layoutManager);
                layoutManager.setOrientation(RecyclerView.VERTICAL);
                MyAdapter myAdapter=new MyAdapter();
                rv.setAdapter(myAdapter);
            }
        });


        return binding.getRoot();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }


    class MyAdapter extends RecyclerView.Adapter<HistoryFragment.MyViewHoder> {

        @NonNull
        @Override
        public HistoryFragment.MyViewHoder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            //View view = View.inflate(getContext(), R.layout.rv_desc_list, null);
            View view =  LayoutInflater.from(getContext()).inflate(R.layout.rv_history_weather, parent, false);
            HistoryFragment.MyViewHoder myViewHoder = new HistoryFragment.MyViewHoder(view);
            return myViewHoder;
        }

        @Override
        public void onBindViewHolder(@NonNull HistoryFragment.MyViewHoder holder, int position) {
            HistoryWeather desc=listData.get(position);
            holder.mCity.setText(desc.getCity());
            holder.mTem.setText(desc.getNowTem());

            Log.i("myDebug", "onBindViewHolder: "+desc.getDate());
            String tmp[]=desc.getDate().split(" ");
            holder.mDate.setText(tmp[0]);
            holder.mTime.setText(tmp[1]);
            holder.chart.setTempDay(desc.getHigh());
            holder.chart.setTempNight(desc.getLow());
            holder.chart.invalidate();
        }

        @Override
        public int getItemCount() {
            return listData.size();
        }
    }

    class MyViewHoder extends RecyclerView.ViewHolder {
        TextView mCity,mTem,mDate,mTime;
        WeatherChartView chart;

        public MyViewHoder(@NonNull View itemView) {
            super(itemView);
            mCity=itemView.findViewById(R.id.history_list_city);
            mTem=itemView.findViewById(R.id.history_list_nowTem);
            mDate=itemView.findViewById(R.id.history_list_date);
            mTime=itemView.findViewById(R.id.history_list_time);
            chart=itemView.findViewById(R.id.history_list_chart);
        }
    }
}